# -*- coding: utf-8 -*-
import sys
import os
import shutil
from PyQt5.QtWidgets import QMainWindow, QApplication, QSystemTrayIcon, QAction, QMenu, QMessageBox
from PyQt5.QtGui import QIcon
from PyQt5 import QtCore
from Conf import ICON_DIR,ROOT
from Comps.Enter import Setup
from Views.Main import Ui_Main
from Pages.Enter import pages, exit
from Core.CC import is_frozen

_py = "Core/Main.py"

class Main:
    def __init__(self, ini, json):
        # 初始化
        self.ini = ini
        self.json = json

        self.icon = None
        self.icon_menu1 = None
        self.icon_menu2 = None
        self.icon_menu3 = None
        self.icon_menu = None
        self.window = None
        self.msg_box = None
        self.pages = {}

        if is_frozen():
            if self.clean_temp_except_self():
                print("缓存清理成功")
            else:
                print("缓存清理失败！")

    def run(self, if_show=True):
        app = QApplication(sys.argv)
        QApplication.setQuitOnLastWindowClosed(False)
        self.window = QMainWindow()
        self.window.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.msg_box = QMessageBox
        self.set_icon()

        gui = Ui_Main()
        gui.setupUi(self.window)

        for key, page in pages.items():
            self.pages[key] = page()

        for page in self.pages.values():
            page.setup(self.ini, self.json, gui, self.pages)

        if if_show:
            self.window.show()
        else:
            self.window.hide()

        app.exec_()

    def setup(self, key, param=None):
        print("安装组件" + key)
        Setup(key, self.ini, self.json, param)

    def set_icon(self):
        self.icon = QSystemTrayIcon(self.window)
        icon_dir = ROOT+ICON_DIR
        try:
            self.icon.setIcon(QIcon(icon_dir))
        except Exception as err:
            print("【err】【" + _py + "-set_icon】 icon图片文件错误")
            return

        self.icon_menu1 = QAction('&显示(Show)', triggered=self.window.show)
        self.icon_menu2 = QAction('&隐藏(Hide)', triggered=self.window.hide)
        self.icon_menu3 = QAction('&退出(Exit)', triggered=self.quit_app)
        self.icon_menu = QMenu()
        self.icon_menu.addAction(self.icon_menu1)
        self.icon_menu.addAction(self.icon_menu2)
        self.icon_menu.addAction(self.icon_menu3)
        self.icon.setContextMenu(self.icon_menu)

        self.icon.activated.connect(self.clk_icon)
        self.icon.show()

    def clk_icon(self, reason):
        # 鼠标点击icon传递的信号会带有一个整形的值，1是表示单击右键，2是双击，3是单击左键，4是用鼠标中键点击
        if reason == 2 or reason == 3:
            self.window.show()

    def quit_app(self):
        re = self.msg_box.question(self.window, "退出", "是否退出", self.msg_box.Yes | self.msg_box.No, self.msg_box.No)
        if re == self.msg_box.Yes:
            self.window.hide()
            self.icon.hide()
            QtCore.QCoreApplication.instance().quit()
            exit()
            sys.exit(0)

    @staticmethod
    def clean_temp_except_self():
        """
        清理PyInstaller临时解压目录的父目录中，除自身外的所有其他文件夹。
        适用于PyInstaller单文件模式打包的程序。
        """
        # 1. 获取当前解压目录 (sys._MEIPASS) _ME开头
        current_temp_dir = getattr(sys, '_MEIPASS', None)

        if not current_temp_dir:
            print("Not running in PyInstaller single-file mode, or _MEIPASS not set.")
            return False

        # 2. 获取父目录（要清理的目标目录）
        parent_dir = os.path.dirname(current_temp_dir)
        if not os.path.isdir(parent_dir):
            print(f"Parent directory does not exist: {parent_dir}")
            return False

        # 3. 获取当前自身的文件夹名（我们要保留的）
        current_folder_name = os.path.basename(current_temp_dir)

        deleted_count = 0
        error_count = 0

        # 4. 遍历父目录下的所有项目
        for item_name in os.listdir(parent_dir):
            item_path = os.path.join(parent_dir, item_name)

            # 只处理文件夹，并且跳过自身
            if os.path.isdir(item_path) and item_name != current_folder_name and item_name.startswith('_MEI'):
                try:
                    shutil.rmtree(item_path)  # 递归删除文件夹及其内容
                    print(f"Successfully deleted: {item_path}")
                    deleted_count += 1
                except Exception as e:
                    print(f"Failed to delete {item_path}: {e}")
                    error_count += 1

        print(f"Cleanup completed. Deleted: {deleted_count}, Errors: {error_count}")
        return True